package com.cx.mall.scheduler.service.impl;

import com.alibaba.fastjson.JSON;
import com.cx.mall.api.seckill.SeckillActivityFeign;
import com.cx.mall.api.seckill.SeckillGoodsFeign;

import com.cx.mall.common.entity.seckill.entity.SeckillActivity;
import com.cx.mall.common.entity.seckill.entity.SeckillGoods;
import com.cx.mall.common.util.ResponseEnum;

import com.cx.mall.common.util.ResponseVo;
import com.cx.mall.scheduler.service.IBuyService;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
@Slf4j
@Service
public class BuyServiceImpl implements IBuyService {
    @Autowired
    private SeckillActivityFeign seckillActivityFeign;
    @Autowired
    private SeckillGoodsFeign seckillGoodsFeign;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void loadStock() {

        try {
            // 测试Redis连接
            try {
                redisTemplate.opsForValue().set("test-connection", "test", 10, TimeUnit.SECONDS);
                String testValue = redisTemplate.opsForValue().get("test-connection");
                if ("test".equals(testValue)) {
                    log.info("Redis连接测试成功");
                } else {
                    throw new RuntimeException("Redis连接测试失败");
                }
            } catch (Exception e) {
                log.error("Redis连接测试失败: {}", e.getMessage(), e);
                throw new RuntimeException("Redis连接失败: " + e.getMessage(), e);
            }



            // 获取所有活动
            ResponseVo ResponseVo = seckillActivityFeign.listAllByToday();
            if (ResponseVo.getCode() != ResponseEnum.SUCCESS.getCode()){
                throw  new RuntimeException(ResponseVo.getMsg());
            }
            List<SeckillActivity> activityList = JSON.parseArray(JSON.toJSONString(ResponseVo.getData()),
                    SeckillActivity.class);
            log.info("获取到活动数量: {}", activityList.size());

            // 遍历所有活动下的商品
            for (SeckillActivity activity : activityList) {
                log.info("开始处理活动: {}", activity.getId());



                ResponseVo result = seckillGoodsFeign.listByActivityById(activity.getId());

                if (result.getCode() != ResponseEnum.SUCCESS.getCode()){
                    throw  new RuntimeException(result.getMsg());
                }
                List<SeckillGoods> seckillGoodsList = JSON.parseArray(JSON.toJSONString(result.getData()),
                        SeckillGoods.class);
                log.info("加载活动:{}商品成功,商品数量为:{}",activity.getId(),seckillGoodsList.size());
                // 加载库存到Redis中
                for (SeckillGoods goods : seckillGoodsList) {

                    // 以seckill+活动id+商品id为key，商品库存为value
                    String key = String.format("seckill-%s-%s",activity.getId(),goods.getSkuId());
                    redisTemplate.opsForValue().set(key,goods.getStoreCount().toString());
                    redisTemplate.expire(key, 1, TimeUnit.DAYS);
                    log.info("加载商品:{}库存成功,库存为:{}",key,goods.getStoreCount());

                }
            }
        } catch (Exception e) {
            log.error("库存预热过程中发生异常", e);
            throw new RuntimeException("库存预热失败: " + e.getMessage(), e);
        }
    }

    @Override
    public void dcount(Integer activityId, String skuId) {
        // 提取商品ID
        String key = "seckill-" + activityId + "-" + skuId;
        // 提取商品库存
        int count = Integer.parseInt(redisTemplate.opsForValue().get(key));
        // 如果库存大于0，则减1
        if(count > 0){
            redisTemplate.opsForValue().decrement(key);
        }else {
            throw new RuntimeException("库存不足");
        }
    }


}